package com.config;

import com.annotaion.Lock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Aspect
@Configuration
@SuppressWarnings("ALL")
public class TimeTaskLockConfig {

    @Autowired
    private RedissonClient redissonClient;

    @Around("@annotation(lock)")
    public Object handler(ProceedingJoinPoint pjp, Lock lock) throws Throwable {
        //锁的名称
        String name=lock.name();

        //等待时间
        long waitTime=lock.waitTime();

        //释放时间
        long leaveTime=lock.leaveTime();

        //得到锁对象
        RLock rLock=redissonClient.getLock(name);

        //试试获取锁
        boolean f=rLock.tryLock(waitTime,leaveTime, TimeUnit.MILLISECONDS);

        Object result=null;
        if (f){
            result=pjp.proceed();  //调用发送消息方法
            Thread.sleep(leaveTime+5000);
        }
        return result;

    }

}
